<template>
  <div class="image-upload">
    <el-upload
      v-model:file-list="fileList"
      :action="uploadUrl"
      :headers="uploadHeaders"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :limit="maxCount"
      :on-exceed="handleExceed"
      list-type="picture-card"
      accept="image/*"
      multiple
    >
      <div class="upload-trigger">
        <el-icon class="upload-icon"><Plus /></el-icon>
        <div class="upload-text">上传图片</div>
      </div>
    </el-upload>
    
    <div class="upload-tips">
      <p>• 支持 JPG、PNG、GIF 格式</p>
      <p>• 单张图片不超过 5MB</p>
      <p>• 最多上传 {{ maxCount }} 张图片</p>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useUserStore } from '@/stores/userStore'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// Props
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  maxCount: {
    type: Number,
    default: 9
  },
  maxSize: {
    type: Number,
    default: 5 * 1024 * 1024 // 5MB
  }
})

// Emits
const emit = defineEmits(['update:modelValue'])

const userStore = useUserStore()

// 文件列表
const fileList = ref([])

// 上传配置
const uploadUrl = computed(() => {
  return import.meta.env.VITE_UPLOAD_URL || '/api/upload/image'
})

const uploadHeaders = computed(() => {
  return {
    Authorization: `Bearer ${userStore.token}`
  }
})

// 监听props变化，初始化文件列表
watch(() => props.modelValue, (newValue) => {
  if (newValue && newValue.length > 0) {
    fileList.value = newValue.map((url, index) => ({
      name: `image-${index}`,
      url: url,
      uid: Date.now() + index
    }))
  } else {
    fileList.value = []
  }
}, { immediate: true })

// 上传前验证
const beforeUpload = (file) => {
  // 检查文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }

  // 检查文件大小
  const isLtMaxSize = file.size < props.maxSize
  if (!isLtMaxSize) {
    ElMessage.error(`图片大小不能超过 ${props.maxSize / 1024 / 1024}MB!`)
    return false
  }

  return true
}

// 上传成功
const handleSuccess = (response, file) => {
  if (response.code === 200) {
    // 更新文件列表中的URL
    const fileIndex = fileList.value.findIndex(item => item.uid === file.uid)
    if (fileIndex !== -1) {
      fileList.value[fileIndex].url = response.data.url
    }
    
    // 更新父组件的值
    updateModelValue()
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.message || '图片上传失败')
    // 移除上传失败的文件
    const fileIndex = fileList.value.findIndex(item => item.uid === file.uid)
    if (fileIndex !== -1) {
      fileList.value.splice(fileIndex, 1)
    }
  }
}

// 上传失败
const handleError = (error, file) => {
  console.error('图片上传失败:', error)
  ElMessage.error('图片上传失败，请重试')
  
  // 移除上传失败的文件
  const fileIndex = fileList.value.findIndex(item => item.uid === file.uid)
  if (fileIndex !== -1) {
    fileList.value.splice(fileIndex, 1)
  }
}

// 移除图片
const handleRemove = (file) => {
  updateModelValue()
}

// 超出限制
const handleExceed = () => {
  ElMessage.warning(`最多只能上传 ${props.maxCount} 张图片`)
}

// 更新父组件的值
const updateModelValue = () => {
  const urls = fileList.value
    .filter(file => file.url && !file.url.startsWith('blob:'))
    .map(file => file.url)
  emit('update:modelValue', urls)
}
</script>

<style scoped>
.image-upload {
  width: 100%;
}

.upload-trigger {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
  transition: all 0.3s ease;
  cursor: pointer;
}

.upload-trigger:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 14px;
  color: #8c939d;
}

.upload-tips {
  margin-top: 10px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #409eff;
}

.upload-tips p {
  margin: 2px 0;
  font-size: 12px;
  color: #666;
}

/* Element Plus 样式覆盖 */
:deep(.el-upload--picture-card) {
  width: 104px;
  height: 104px;
  border-radius: 6px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 104px;
  height: 104px;
  border-radius: 6px;
}

:deep(.el-upload-list__item-thumbnail) {
  object-fit: cover;
}

/* 响应式设计 */
@media (max-width: 768px) {
  :deep(.el-upload--picture-card) {
    width: 80px;
    height: 80px;
  }
  
  :deep(.el-upload-list--picture-card .el-upload-list__item) {
    width: 80px;
    height: 80px;
  }
  
  .upload-icon {
    font-size: 20px;
  }
  
  .upload-text {
    font-size: 12px;
  }
}
</style>